<template>
  <div style="min-height: 600px;" class="tyvex">
    <el-row>
      <el-col :span="24">
        <el-button-group>
          <el-button size="small" type="primary" :icon="Plus" @click="NewRule">新增</el-button>
          <el-button size="small" type="primary" :icon="DocumentCopy">复制</el-button>
          <el-button size="small" type="primary" :icon="Edit">修改</el-button>
          <el-button size="small" type="primary" :icon="Delete" @click="Deletet">删除</el-button>
          <el-button size="small" type="primary" :icon="Check">启用</el-button>
          <el-button size="small" type="primary" :icon="Close" @click="test">停用</el-button>
        </el-button-group>
        <el-button style="margin-left:20px ;" size="small" type="primary" @click="onSubmit">保存</el-button>
      </el-col>
      <el-col style="margin-top: 10px;" :span="6">
        <el-tabs type="border-card" v-model="selectTab" style="height: 100%;" @tab-change="handleClick">
          <el-tab-pane label="取数" style="height: 100%;" name="select">
            <vxe-table border keep-source width="100%"  :height="windowHeight-310" ref="selectRule" size="mini" :data="selectRuleData"
                       @cell-click="getTabaleClick" :row-config="{isCurrent: true, isHover: true}">
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="ruleName" title="规则名称" width="180"></vxe-column>
              <vxe-column field="ruleType" title="规则类型" width="120"></vxe-column>
              <vxe-column field="runTime" title="执行时机" width="160"></vxe-column>
              <vxe-column field="workflowID" title="工作流名称" width="160"></vxe-column>
              <vxe-column field="activityName" title="任务节点名称" width="160"></vxe-column>
              <vxe-column field="isActive" title="启用" width="60"></vxe-column>
              <vxe-column field="memo" title="备注" width="160"></vxe-column>
            </vxe-table>
          </el-tab-pane>
          <!-- <el-tab-pane label="下推" style="height: 100%;" name="pushDown">
            <vxe-table border keep-source  :height="windowHeight-310" width="100%" ref="transferRule" size="mini"
                       :data="[]" @cell-click="getTabaleClick"
                       :row-config="{isCurrent: true, isHover: true}">
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="ruleName" title="规则名称" width="180"></vxe-column>
              <vxe-column field="ruleType" title="规则类型" width="120"></vxe-column>
              <vxe-column field="runTime" title="执行时机" width="160"></vxe-column>
              <vxe-column field="workflowID" title="工作流名称" width="160"></vxe-column>
              <vxe-column field="activityName" title="任务节点名称" width="160"></vxe-column>
              <vxe-column field="isActive" title="启用" width="60"></vxe-column>
              <vxe-column field="memo" title="备注" width="160"></vxe-column>
            </vxe-table>
          </el-tab-pane> -->
          <el-tab-pane label="更新" style="height: 100%;" name="update">
            <vxe-table border keep-source  :height="windowHeight-310" width="100%" ref="updateRule" size="mini" :data="updateRuleData"
                       @cell-click="getTabaleClick" :row-config="{isCurrent: true, isHover: true}">
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="ruleName" title="规则名称" width="180"></vxe-column>
              <vxe-column field="ruleType" title="规则类型" width="120"></vxe-column>
              <vxe-column field="runTime" title="执行时机" width="160"></vxe-column>
              <vxe-column field="workflowID" title="工作流名称" width="160"></vxe-column>
              <vxe-column field="activityName" title="任务节点名称" width="160"></vxe-column>
              <vxe-column field="isActive" title="启用" width="60"></vxe-column>
              <vxe-column field="memo" title="备注" width="160"></vxe-column>
            </vxe-table>
          </el-tab-pane>
          <el-tab-pane label="传送" style="height: 100%;" name="transfer">
            <vxe-table border keep-source  :height="windowHeight-310" width="100%" ref="transferRule" size="mini"
                       :data="transferRuleData" @cell-click="getTabaleClick"
                       :row-config="{isCurrent: true, isHover: true}">
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="ruleName" title="规则名称" width="180"></vxe-column>
              <vxe-column field="ruleType" title="规则类型" width="120"></vxe-column>
              <vxe-column field="runTime" title="执行时机" width="160"></vxe-column>
              <vxe-column field="workflowID" title="工作流名称" width="160"></vxe-column>
              <vxe-column field="activityName" title="任务节点名称" width="160"></vxe-column>
              <vxe-column field="isActive" title="启用" width="60"></vxe-column>
              <vxe-column field="memo" title="备注" width="160"></vxe-column>
            </vxe-table>
          </el-tab-pane>
          <el-tab-pane label="通知" style="height: 100%;" name="sendMsg">
            <vxe-table border keep-source  :height="windowHeight-310" width="100%" ref="transferRule" size="mini"
                       :data="sendMsgRuleData" @cell-click="getTabaleClick"
                       :row-config="{isCurrent: true, isHover: true}">
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="ruleName" title="规则名称" width="180"></vxe-column>
              <vxe-column field="ruleType" title="规则类型" width="120"></vxe-column>
              <vxe-column field="runTime" title="执行时机" width="160"></vxe-column>
              <vxe-column field="workflowID" title="工作流名称" width="160"></vxe-column>
              <vxe-column field="activityName" title="任务节点名称" width="160"></vxe-column>
              <vxe-column field="isActive" title="启用" width="60"></vxe-column>
              <vxe-column field="memo" title="备注" width="160"></vxe-column>
            </vxe-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col style="margin-top: 10px;height:100%;" :span="18">
        <el-tabs v-show="selectTab==='select'" type="border-card" style="height: 100%;">
          <el-tab-pane label="基本信息" >
            <vxe-form
                title-colon
                ref="xForm"
                title-align="right"
                title-width="100"
                :data="selectForm">
              <vxe-form-gather span="24">
                <vxe-form-item title="名称" field="ruleName" span="12" title-width="60"
                               :item-render="{name:'$input',props:{placeholder:'名称将作为按钮名称'}}"></vxe-form-item>
                <vxe-form-item title="启用" field="isActive" span="6"
                               :item-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"
                               title-overflow="ellipsis"></vxe-form-item>
                <vxe-form-item title="排序" field="runSeq" span="6" title-width="60"
                               :item-render="{name:'$input', props:{type:'integer',placeholder:'排序'}}"></vxe-form-item>
              </vxe-form-gather>

              <vxe-form-gather span="12">
                <vxe-form-item title="" field="runTime" :item-render="{}">
                  <template #default="{ data }">
                    <el-card class="box-card" shadow="never">
                      <div slot="header" class="clearfix">
                        <span>执行时机</span>
                      </div>
                      <vxe-checkbox-group v-model="data.runTime" class="xxz">
                          <vxe-checkbox style="margin-left: 10px;" label="999" content="手动执行"></vxe-checkbox>
                          <vxe-checkbox label="101" content="新增表单打开时"></vxe-checkbox>
                          <vxe-checkbox label="102" content="复制新增表单打开时"></vxe-checkbox>
                          <vxe-checkbox label="103" content="修改表单打开时"></vxe-checkbox>
                          <vxe-checkbox label="104" content="重存表单打开时"></vxe-checkbox>
                          <vxe-checkbox label="105" content="查阅表单打开时"></vxe-checkbox>
                          <vxe-checkbox label="106" content="筛选条件改变后"></vxe-checkbox>
                          <vxe-checkbox label="107" content="保存前"></vxe-checkbox>
                          <vxe-checkbox label="108" content="查询时"></vxe-checkbox>
                          <vxe-checkbox label="109" content="提交前"></vxe-checkbox>
                          <vxe-checkbox label="110" content="工作流"></vxe-checkbox>
                          <vxe-checkbox label="212" content="定时任务"></vxe-checkbox>
                      </vxe-checkbox-group>
                      <vxe-select width="300" v-model="selectForm['onChangeFileld']" placeholder="字段变更时执行"   clearable multiple transfer>
                        <vxe-optgroup v-for="(tb ,name) in Fields" :label="tb.tableDispName" :key="name">
                          <vxe-option v-for="(item,index) in tb.Children" :key="index" :value="item.fieldName"
                                      :label="tb.tableDispName+'.'+item.fieldDispName"></vxe-option>
                        </vxe-optgroup>
                      </vxe-select>
                    </el-card>
                  </template>
                </vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="12">
                <vxe-form-item title="" :item-render="{}">
                  <template #default="{ data }">
                    <el-card class="box-card" shadow="never">
                      <div slot="header" class="clearfix">
                        <span>其它选项</span>
                      </div>
                        <p> <vxe-checkbox v-model="data.clearAllRow" :checked-value=1 :unchecked-value=0>执行前清空所在区域所有数据</vxe-checkbox></p>
                        <p> <vxe-checkbox v-model="selectForm.sendInfo.getDefault" :checked-value=1 :unchecked-value=0>加载后取默认值</vxe-checkbox></p>

                    </el-card>
                  </template>
                </vxe-form-item>
              </vxe-form-gather>
            </vxe-form>
          </el-tab-pane>
          <el-tab-pane label="取数来源及条件" style="height: 100%;">
            <vxe-radio name="n1" v-model="selectForm.sourceType" :label="1" content="查询SQL" size="mini"></vxe-radio>
            <vxe-radio name="n1" v-model="selectForm.sourceType" :label="2" content="模版" size="mini"></vxe-radio>
            <vxe-radio name="n1" v-model="selectForm.sourceType" :label="3" content="外部API" size="mini"></vxe-radio>
            <div v-if="selectForm.sourceType==1">
              <el-row>
                <el-col :span="10">
                  <vxe-form
                      title-colon
                      ref="xForm"
                      title-align="right"
                      title-width="100"
                      :data="selectForm">
                    <vxe-form-item field="toDB" :item-render="{defaultValue:''}" title="来源数据库">
                      <template #default>
                        <vxe-select v-model="selectForm.dB" transfer>
                          <vxe-option v-for="item in db" :key="item.value" :value="item.value"
                                      :label="item.label"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="" field="sqlSchema" span="24" :item-render="{}">
                      <template #default>
                        <div>查询SQL
                          <vxe-button size="mini" status="primary" style="position: absolute;top: -9px;right: 0;" icon="el-icon-edit" @click="gettestSql()">测试并生成字段
                          </vxe-button>
                        </div>
                        <vxe-textarea v-model="selectForm.sqlSchema" placeholder="请输入SQL" :autosize="{minRows: 12, maxRows: 12}"></vxe-textarea>
                      </template>
                    </vxe-form-item>
                  </vxe-form>
                </el-col>
                <el-col :span="14">
                  <vxe-table
                      border
                      size="mini"
                      ref="sourceFieldsSql"
                      :height="tabelheight/2"
                      :row-config="{isHover: true}"
                      :edit-config="{trigger: 'click', mode: 'cell'}"
                      @cell-dblclick="rowclick2"
                      :data="selectForm.sourceField">
                    <vxe-column type="seq" width="40"></vxe-column>
                    <vxe-column field="field" title="字段"></vxe-column>
                    <vxe-column field="fieldType" title="类型" :edit-render="{name:'$select',options:datatype}"></vxe-column>
                  </vxe-table>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <vxe-table
                      v-if="ToFields[0]!=null"
                      show-overflow
                      size="mini"
                      ref="sourceFieldsSql"
                      :tree-config="{expandAll:true}"
                      @cell-dblclick="rowclick2"
                      :height="tabelheight/2+10"
                      :data="ToFields">
                    <vxe-column field="title" title="双击选择条件字段" tree-node></vxe-column>
                  </vxe-table>
                </el-col>
                <el-col :span="10">
                  <vxe-form
                      title-align="right"
                      title-width="100"
                      :data="selectForm">
                    <vxe-form-item title="" field="filterExpr" span="24" :item-render="{}">
                      <template #default>
                        <div>前端取数条件</div>
                        <vxe-textarea v-model="selectForm.filterExpr" placeholder="请输入条件"
                                      :autosize="{minRows: 4, maxRows: 4}"></vxe-textarea>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="" field="filterExpr" span="24" :item-render="{}">
                      <template #default>
                        <div>后台取数条件</div>
                        <vxe-textarea v-model="selectForm.sendInfo.backFilter" placeholder="请输入条件"
                                      :autosize="{minRows: 4, maxRows: 4}"></vxe-textarea>
                      </template>
                    </vxe-form-item>
                  </vxe-form>
                </el-col>
              </el-row>
            </div>
            <div v-if="selectForm.sourceType==2" class="ju">
              <el-row>
                <el-col :span="6" class="bor">
                  <vxe-table
                      show-overflow
                      ref="xTree"
                      size="mini"
                      :show-header="false"
                      height="250px"
                      :tree-config="{}"
                      keep-source
                      :row-config="{isCurrent: true, isHover: true}"
                      @cell-dblclick="setSelectTable"
                      :data="sourceTableData">
                    <vxe-column field="title" tree-node ></vxe-column>
                  </vxe-table>
                  <p class="prompt">已选择数据表</p>
                  <vxe-table
                      show-overflow
                      ref="selectTables"
                      size="mini"
                      keep-source
                      height="150px"
                      :show-header="false"
                      @cell-dblclick="TableChangeEventDelete"
                      :row-config="{isCurrent: true, isHover: true}"
                      :data="sqlSchema.selectTablesData">
                    <vxe-column field="title"></vxe-column>
                  </vxe-table>
                </el-col>
                <el-col class="bor" :span="18">
                  <div class="viewbuton">
                    <span>筛选条件：</span>
                    <el-button type="primary" size="default" @click="showchose2">条件表达式</el-button>
                  </div>
                  <el-input
                      type="textarea"
                      :rows="8"
                      placeholder="请输入内容"
                      v-model="selectForm['filterExpr']">
                  </el-input>
                  <div class="viewbuton">
                    <span>表间关系：</span>
                    <el-button type="primary" size="default" @click="newRlations">新建表间关联</el-button>
                  </div>
                  <vxe-table
                      show-overflow
                      ref="selectRelations"
                      size="mini"
                      keep-source
                      :tree-config="{}"
                      height="194px"
                      :row-config="{isCurrent: true, isHover: true}"
                      :data="sqlSchema.relationsData"
                      :edit-config="{trigger: 'click', mode: 'cell', icon: 'fa fa-pencil', showStatus: true}">
                    <vxe-column field="relationType" title="关联" :edit-render="{name:'$select',options:[{label:'LEFT JOIN',value:'Left Join'},{label:'RIGHT JOIN',value:'RIGHT JOIN'},{label:'INNER JOIN',value:'INNER JOIN'},]}"></vxe-column>
                    <vxe-column field="tableDispName2" title="表2" :cell-render="{}">
                      <template #default="{ row }">
                        <vxe-select v-model="row['tableDispName2']" placeholder="下拉框" clearable transfer>
                          <vxe-option v-for="(it,index) in SelectTableToChoice" :value="it.name" :label="it.title" :key="index"></vxe-option>
                          <vxe-option v-for="(it,index) in ToFields.filter(row=>row.tp===1)" :value="it.name" :label="it.title" :key="index"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-column>
                    <vxe-column field="relationExpr" title="关联条件" :edit-render="{name:'$input',events:{click:showchose}}"></vxe-column>
                    <vxe-column title="操作" width="100" show-overflow>
                      <template #default="{ row }">
                        <vxe-button type="text" icon="fa fa-trash-o" @click="selectRelationsremove(row)"></vxe-button>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </el-col>
              </el-row>
            </div>
            <div v-if="selectForm.sourceType==3">

              <vxe-form :data="selectForm">
                <vxe-form-item title="Api网址" field="dB"  span="24" :item-render="{}">
                  <template #default>
                    <vxe-input v-model="selectForm.dB" placeholder="请输入网址" clearable></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="" field="filterExpr" span="24" :item-render="{}">
                  <template #default>
                    <span>取数参数:</span>
                    <vxe-textarea v-model="selectForm.filterExpr" placeholder="取数参数" clearable :autosize="{minRows: 6, maxRows: 6}"></vxe-textarea>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="" field="sourceField" span="24" :item-render="{}">
                  <template #default>
                    <span>来源json样本:</span>
                    <vxe-textarea v-model="selectForm.sourceField" placeholder="来源json样本" clearable :autosize="{minRows: 10, maxRows:10}"></vxe-textarea>
                  </template>
                </vxe-form-item>
              </vxe-form>

            </div>
          </el-tab-pane>
          <el-tab-pane label="填充方式" style="height: 100%;">
            <el-row>
              <el-col :span="4">
                <vxe-table
                    show-overflow
                    ref="ChoseTableFields1"
                    size="mini"
                    :height="tabelheight"
                    :tree-config="{}"
                    @cell-dblclick="rowclick1"
                    :data="ToFields">
                  <vxe-column field="title" title="双击选择表字段" tree-node></vxe-column>
                </vxe-table>
              </el-col>
              <el-col :span="20">
                <vxe-table
                    border
                    size="mini"
                    ref="SelectTableFields"
                    :height="tabelheight"
                    width="100%"
                    :row-config="{isHover: true}"
                    @cell-click="doselectRow"
                    :data="selectForm.targetField">
                  <vxe-column type="seq" width="40"></vxe-column>
                  <vxe-column field="tofield" title="字段" width="220" :cell-render="{}">
                    <template #default="{ row }">
                      <vxe-select v-model="row.tofield" placeholder="分组" clearable transfer @change="changeToField">
                        <vxe-optgroup v-for="(tb ,name) in Fields" :label="tb.tableDispName" :key="name">
                          <vxe-option v-for="(item,index) in tb.Children" :key="index" @change="changeToField"
                                      :value="tb.tableName+'.'+item.fieldName"

                                      :label="item.fieldDispName"></vxe-option>
                        </vxe-optgroup>

                      </vxe-select>
                    </template>
                  </vxe-column>
                  <vxe-column field="field" title="对应字段" width="160" :cell-render="{}">
                    <template #default="{ row }">
                      <vxe-select v-model="row.field" placeholder="选择字段" clearable transfer  filterable :filter-method="fieldchoice">
                        <vxe-optgroup v-if="selectForm.sourceField.length>0" label="取数来源" >
                          <vxe-option v-for="(item,index) in selectForm.sourceField" :key="index" :value="item.field" :label="item.field"></vxe-option>
                        </vxe-optgroup>
                        <vxe-optgroup v-for="(tb ,name) in Fields" :label="tb.tableDispName" :key="name">
                          <vxe-option v-for="(item,index) in tb.Children" :key="index" :value="tb.tableName+'.'+item.fieldName" :label="item.fieldDispName"></vxe-option>
                        </vxe-optgroup>
                        <vxe-optgroup v-for="(tb ,name) in SelectTableToChoice" :label="tb.title" :key="name">
                          <vxe-option v-for="(item,index) in tb.children" :key="index"
                                      :value="item.name" :label="item.title"></vxe-option>
                        </vxe-optgroup>
                      </vxe-select>
                    </template>
                  </vxe-column>
                  <vxe-column field="type" title="填写方式" width="100" :cell-render="{typedefaultValue:'value'}">
                    <template #default="{ row }">
                      <vxe-select v-model="row.type" placeholder="填写方式" clearable transfer>
                        <vxe-option value="value" label="填写值"></vxe-option>
                        <vxe-option value="keys" label="关联匹配"></vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-column>
                  <vxe-column field="query" title="查询时条件" width="160" :cell-render="{}">
                    <template #default="{ row }">
                      <vxe-select v-model="row.query" placeholder="条件" clearable transfer>
                        <vxe-option v-for="(item,index) in Filter" :key="index" :value="item.type"
                                    :label="item.title"></vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-column>
                  <vxe-column width="60" :cell-render="{}">
                    <template #default="{ row }">
                      <el-button size="small" type="primary" :icon="Delete"
                                 @click="SelectTableFields.remove(row)"></el-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <el-tabs v-show="selectTab==='update'" type="border-card" style="height: 100%;">
          <el-tab-pane label="更新设置" style="height: 100%;">
            <vxe-form
                title-colon
                title-align="right"
                title-width="100"
                :data="updateForm">
              <vxe-form-item title="规则名称" field="ruleName" span="18" :item-render="{name:'input'}"
                             title-overflow="ellipsis"></vxe-form-item>
              <vxe-form-item title="启用" field="isActive" span="6"
                             :item-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"
                             title-overflow="ellipsis"></vxe-form-item>
              <vxe-form-gather span="8">
                <vxe-form-item field="runTime" span="24" :item-render="{}">
                  <template #default>
                    <div style="margin-left: 20px">执行时机</div>
                    <vxe-checkbox-group v-model="updateForm.runTime" class="xxz">
                      <vxe-checkbox style="margin-left: 10px;" label="999" content="手动执行"></vxe-checkbox>
                      <vxe-checkbox style="margin-left: 10px;" label="201" content="第一次保存后"></vxe-checkbox>
                      <vxe-checkbox label="202" content="每一次保存后"></vxe-checkbox>
                      <vxe-checkbox label="203" content="修改保存前"></vxe-checkbox>
                      <vxe-checkbox label="204" content="删除前"></vxe-checkbox>
                      <vxe-checkbox label="205" content="撤消前"></vxe-checkbox>
                      <vxe-checkbox label="206" content="审核后"></vxe-checkbox>
                      <vxe-checkbox label="207" content="反审后"></vxe-checkbox>
                      <vxe-checkbox label="208" content="作废后"></vxe-checkbox>
                      <vxe-checkbox label="209" content="反作废后"></vxe-checkbox>
                      <vxe-checkbox label="210" content="归档后"></vxe-checkbox>
                      <vxe-checkbox label="211" content="导入后"></vxe-checkbox>
                        <vxe-checkbox label="213" content="打印后"></vxe-checkbox>
                        <vxe-checkbox label="212" content="定时任务"></vxe-checkbox>
                    </vxe-checkbox-group>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="审核状态" :visible="updateForm.runTime&&updateForm.runTime.includes('206')" field="isSend"  :item-render="{}">
                  <template #default="{ data }">
                    <vxe-radio-group v-model="data.isSend">
                      <vxe-radio :label="0" content="成功"></vxe-radio>
                      <vxe-radio :label="4" content="失败"></vxe-radio>
                    </vxe-radio-group>
                  </template>
                </vxe-form-item>
                <vxe-form-item field="toDB" :item-render="{}">
                  <template #default>
                    <div>作用数据库</div>
                    <vxe-select v-model="updateForm.dB" transfer>
                      <vxe-option v-for="item in db" :key="item.value" :value="item.value"
                                  :label="item.label"></vxe-option>
                    </vxe-select>
                  </template>
                </vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="16">
                <vxe-form-item title="" field="sqlSchema" span="24" :item-render="{}">
                  <template #default>
                    <div>更新语句</div>
                    <vxe-textarea v-model="updateForm.sqlSchema" placeholder="请输入更新语句"
                                  :autosize="{minRows: 15, maxRows: 15}" clearable></vxe-textarea>
                    <div>@RecordID 为当前表关键字</div>
                  </template>
                </vxe-form-item>

              </vxe-form-gather>
            </vxe-form>
          </el-tab-pane>
          <el-tab-pane label="更新脚本">


          </el-tab-pane>
        </el-tabs>
        <el-tabs v-show="selectTab==='transfer'" type="border-card" style="height: 100%;">
          <el-tab-pane label="基本信息" style="height: 100%;">
            <vxe-form
                title-colon
                ref="transferFormt"
                title-align="right"
                title-width="100"
                :data="transferForm">
              <vxe-form-gather span="24">
                <vxe-form-item title="名称" field="ruleName" span="6" title-width="60" :item-render="{name:'$input',props:{placeholder:''}}"></vxe-form-item>
                <vxe-form-item title="类型" field="sourceType" span="6" title-width="60" :item-render="{name:'$select',defaultValue:0,options:[{label:'Api',value:0},{label:'钉钉',value:1},{label:'企业微信',value:2},{value:3,label:'金蝶'}]}"></vxe-form-item>
                <vxe-form-item title="启用" field="isActive" span="6" :item-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"
                               title-overflow="ellipsis"></vxe-form-item>
                <vxe-form-item title="外部流程" field="isExtFlow" span="6" :item-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"
                               title-overflow="ellipsis"></vxe-form-item>
              </vxe-form-gather>

              <vxe-form-gather span="24" v-if="transferForm.sourceType===0">
                <vxe-form-item title="方式" field="sendInfo.method" span="6" title-width="60" :item-render="{name:'$select',defaultValue:0,options:[{label:'POST+Json',value:1},{label:'POST+XML',value:2}]}"></vxe-form-item>
                <vxe-form-item title="结果信息" field="sendInfo.StatusFlag" span="6"  :item-render="{name:'$input',props:{placeholder:'多字段用,分隔'}}"></vxe-form-item>
                <vxe-form-item title="保存到主表" field="sendInfo.saveField" span="6"  :item-render="{}">
                  <template #default="{ data }">
                    <vxe-select multiple v-model="data.sendInfo.saveField" placeholder="默认不保存" clearable transfer>
                      <vxe-option value="" label="不保存"></vxe-option>
                        <vxe-option v-for="(item,index) in Fields[0].Children" :key="index"
                                    :value="item.fieldName"
                                    :label="item.fieldDispName"></vxe-option>
                    </vxe-select>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="URL" field="sendInfo.Url" span="24" title-width="60" :item-render="{name:'$input',props:{placeholder:'接口地址'}}"></vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="24" v-if="transferForm.sourceType===3">
                <vxe-form-item title="URL" field="sendInfo.Url" span="24" title-width="60" :item-render="{name:'$input',props:{placeholder:'接口地址'}}"></vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="24" v-if="transferForm.sourceType===1 ">
                <vxe-form-item title="钉钉表单" field="sendInfo.proc" span="14" title-width="80" filterable clearable :item-render="{}">
                  <template #default="{ data }">
                    <vxe-select v-model="data.sendInfo.proc" placeholder="请选择表单">
                      <vxe-option v-for="(item, index) in dingforms" :key="index" :value="item.value" :label="item.label"></vxe-option>
                    </vxe-select>
                  </template>
                </vxe-form-item>
                <vxe-form-item align="center" span="3">
                  <template #default> <vxe-button status="primary" content="取钉钉表单" @click="getDingForms"></vxe-button> </template>
                </vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="24" v-if="transferForm.sourceType===2 ">
               <vxe-form-item title="企业微信表单" field="sendInfo.proc" span="20" title-width="120" :item-render="{name:'$input',props:{placeholder:'企业微信表单'}}"></vxe-form-item>
                <vxe-form-item align="center" span="3">
                  <template #default> <vxe-button status="primary" content="下载表单" @click="getWxForms"></vxe-button> </template>
                </vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="24">
                <vxe-form-item title="" field="runTime" :item-render="{}">
                  <template #default="{ data }">
                    <el-card class="box-card" shadow="never">
                      <div slot="header" class="clearfix">
                        <span>执行时机</span>
                      </div>
                      <vxe-checkbox-group v-model="data.runTime" class="xxz">
                        <vxe-checkbox style="margin-left: 10px;" label="999" content="手动执行"></vxe-checkbox>
                        <vxe-checkbox label="201" content="第一次保存后"></vxe-checkbox>
                        <vxe-checkbox label="202" content="每一次保存后"></vxe-checkbox>
                        <vxe-checkbox label="203" content="修改保存前"></vxe-checkbox>
                        <vxe-checkbox label="204" content="删除前"></vxe-checkbox>
                        <vxe-checkbox label="205" content="撤消前"></vxe-checkbox>
                        <vxe-checkbox label="206" content="审核后"></vxe-checkbox>
                        <vxe-checkbox label="207" content="反审后"></vxe-checkbox>
                        <vxe-checkbox label="208" content="作废后"></vxe-checkbox>
                        <vxe-checkbox label="209" content="反作废后"></vxe-checkbox>
                        <vxe-checkbox label="210" content="归档后"></vxe-checkbox>
                          <vxe-checkbox label="211" content="导入后"></vxe-checkbox>
                          <vxe-checkbox label="213" content="打印后"></vxe-checkbox>
                          <vxe-checkbox label="212" content="定时任务"></vxe-checkbox>

                      </vxe-checkbox-group>
                    </el-card>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="审核状态" :visible="transferForm.runTime&&transferForm.runTime.includes('206')" field="isSend"  :item-render="{}">
                  <template #default="{ data }">
                    <vxe-radio-group v-model="data.isSend">
                      <vxe-radio :label="0" content="成功"></vxe-radio>
                      <vxe-radio :label="4" content="失败"></vxe-radio>
                    </vxe-radio-group>
                  </template>
                </vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="20" style="padding: 10px; box-sizing: border-box;">

                <vxe-form-item title="消息通知" field="sendInfo.sendMsg" span="24"   :item-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"></vxe-form-item>
                <vxe-form-item   title="通知对象" field="sendTo" span="24" :item-render="{}">
                  <template #default="{ data }">
                    <vxe-select v-model="data.sendInfo.sendTo" placeholder="请选择方式" clearable transfer>
                      <vxe-option value="DingTalk" label="钉钉"></vxe-option>
                    </vxe-select>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="消息方式" field="msgType" span="12" :item-render="{}">
                  <template #default="{ data }">
                    <vxe-select multiple v-model="data.sendInfo.msgType" placeholder="请选择方式" clearable transfer>
                      <vxe-option value="TZ" label="应用通知"></vxe-option>
                      <vxe-option value="DB" label="待办消息"></vxe-option>
                      <vxe-option value="PL" label="审批评论"></vxe-option>
                    </vxe-select>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="通知信息" field="msgStruct" span="24" :item-render="{}">
                  <template #default="{ data }">
                    <vxe-select multiple v-model="data.sendInfo.msgStruct" placeholder="分组" clearable transfer>
                      <vxe-optgroup v-for="(tb ,name) in Fields" :label="tb.tableDispName" :key="name">
                        <vxe-option v-for="(item,index) in tb.Children" :key="index"
                                    :value="tb.tableName+'.'+item.fieldName"
                                    :label="tb.tableDispName+'.'+item.fieldDispName"></vxe-option>
                      </vxe-optgroup>
                    </vxe-select>
                  </template>
                </vxe-form-item>
              </vxe-form-gather>
            </vxe-form>
          </el-tab-pane>
          <el-tab-pane label="填充方式" style="height: 100%;">
            <el-row>
              <el-col :span="4">
                <vxe-table
                    show-overflow
                    ref="ChoseTableFields1"
                    size="mini"
                    :height="windowHeight-310"
                    :tree-config="{expandAll: true}"
                    @cell-dblclick="rowclick"
                    :data="ToFields">
                  <vxe-column field="title" title="双击选择表字段" tree-node></vxe-column>
                </vxe-table>

              </el-col>
              <el-col :span="20">
                <el-button-group>
                  <el-button size="small" type="primary" icon="el-icon-caret-top"
                             @click="transferTree1.setAllTreeExpand(true)">左侧展开
                  </el-button>
                  <el-button size="small" type="primary" v-if="transferForm.sourceType===1"  @click="copytitle()">生成钉钉默认字段</el-button>
                  <el-button size="small" type="primary" v-if="transferForm.sourceType===0"  @click="loadDef()">加载默认</el-button>
                  <el-button size="small" type="primary" @click="addNew(0)">添加</el-button>
                  <el-button size="small" type="primary" >启用</el-button>
                  <el-button size="small" type="primary"  @click="test">停用</el-button>
                </el-button-group>
                <vxe-table
                    border
                    size="mini"
                    ref="transferDatat"
                    :max-height="windowHeight-310"
                    :row-config="{isCurrent: true, isHover: true,useKey:true}"
                    :tree-config="{expandAll: true,indent:5}"
                    :data="transferForm.sqlSchema">
                  <vxe-column  tree-node type="seq" width="120" > </vxe-column>
                  <vxe-column width="80" title="来源">
                    <template #default="{ row }">{{row.name}}</template>
                  </vxe-column>
                  <vxe-column field="name" title="来源数据">
                    <template #default="{ row }">
                      <vxe-input size="mini" v-if="row.type==='DefineText'||row.type==='DefineNumber'" v-model="row.name" placeholder="自定义值" />
                      <vxe-select v-else v-model="row.name" placeholder="选择字段" clearable transfer  filterable :filter-method="fieldchoice" @change="({value })=>{changeField(value,row)}">
                        <vxe-optgroup v-for="(tb ,name) in Fields" :label="tb.tableDispName" :key="name">
                          <vxe-option v-for="(item,index) in tb.Children" :key="index" :value="item.fieldName" :label="item.fieldDispName"></vxe-option>
                        </vxe-optgroup>
                        <vxe-optgroup label="选择表">
                          <vxe-option v-for="(item,index) in Fields" :key="index"  :value="item.tableName" :label="item.tableDispName"></vxe-option>
                        </vxe-optgroup>
                      </vxe-select>

                    </template>
                  </vxe-column>

                  <vxe-column field="type" title="类型" >
                    <template #default="{ row }">
                      <vxe-select v-model="row.type" placeholder="请选择类型" transfer>
                        <vxe-option v-for="(item, index) in datatype" :key="index" :value="item.value" :label="item.label"  v-if="transferForm.sourceType===0" ></vxe-option>
                        <vxe-option v-for="(item, index) in dingtypes" :key="index" :value="item.value" :label="item.label"  v-if="transferForm.sourceType===1" ></vxe-option>
                        <vxe-option v-for="(item, index) in datatype" :key="index" :value="item.value" :label="item.label"  v-if="transferForm.sourceType===2" ></vxe-option>
                      </vxe-select>
                      <vxe-input v-if="row.type==='Table'" size="mini" v-model="row.link" placeholder="上级表额外关联" />
                    </template>
                  </vxe-column>
                   <vxe-column field="field" title="字段" v-if="transferForm.sourceType===2" >
                    <template #default="{ row }" >
                      <vxe-select v-model="row.field" placeholder="请选择类型" transfer v-if="busthguy(row)==null&&row.type!='Table'">
                        <vxe-option v-for="(item) in textoption" :key="item.id" :value="item" :label="item.title" ></vxe-option>
                      </vxe-select>
                      <vxe-select v-model="row.field" placeholder="请选择类型" transfer v-if="busthguy(row)=='Table'">
                        <vxe-option v-for="item in tableoption" :key="item.id" :value="item" :label="item.title" >
                        </vxe-option>
                      </vxe-select>
                      <vxe-select v-model="row.field" placeholder="请选择类型" transfer v-if="row.type=='Table'" @change="clicktable">
                          <vxe-option v-for="(item) in tableoption2" :key="item.id" :value="item" :label="item.title"></vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-column>
                  <vxe-column v-else field="field" title="接口字段">
                    <template #default="{ row }" >
                      <vxe-input size="mini" v-model="row.field" placeholder="接口字段" />
                    </template>
                  </vxe-column>
                  <vxe-column title="操作" width="200" show-overflow>
                    <template #default="{ row }">
                      <el-button type="primary" size="small"  @click="add(row,0)">平级</el-button>
                      <el-button type="primary" size="small"  @click="add(row,1)">下级</el-button>
                      <el-button type="danger" size="small"  @click="remove(row)">删除</el-button>

                    </template>
                  </vxe-column>
                </vxe-table>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <el-tabs v-show="selectTab==='sendMsg'" type="border-card" style="height: 100%;">
          <el-tab-pane label="通知设置" style="height: 100%;">
            <vxe-form
                title-colon
                title-align="right"
                title-width="100"
                :data="sendMsgForm">
              <vxe-form-item title="规则名称" field="ruleName" span="18" :item-render="{name:'input'}"
                             title-overflow="ellipsis"></vxe-form-item>
              <vxe-form-item title="启用" field="isActive" span="6"
                             :item-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"
                             title-overflow="ellipsis"></vxe-form-item>
              <vxe-form-item title="执行类型" field="sourceType" span="24" :item-render="{name:'$select',props:{clearable:true},defaultValue:0,options:[{label:'通知',value:0},{label:'字段修改',value:1}]}"></vxe-form-item>

              <vxe-form-item title="执行时机" field="runTime" span="24" :item-render="{}">
                  <template #default>
                    <vxe-checkbox-group v-model="sendMsgForm.runTime" class="xxz">
                      <vxe-checkbox style="margin-left: 10px;" label="999" content="手动执行"></vxe-checkbox>
                      <vxe-checkbox style="margin-left: 10px;" label="201" content="第一次保存后"></vxe-checkbox>
                      <vxe-checkbox label="202" content="每一次保存后"></vxe-checkbox>
                      <vxe-checkbox label="203" content="修改保存前"></vxe-checkbox>
                      <vxe-checkbox label="204" content="删除前"></vxe-checkbox>
                      <vxe-checkbox label="205" content="撤消前"></vxe-checkbox>
                      <vxe-checkbox label="206" content="审核后"></vxe-checkbox>
                      <vxe-checkbox label="207" content="反审后"></vxe-checkbox>
                      <vxe-checkbox label="208" content="作废后"></vxe-checkbox>
                      <vxe-checkbox label="209" content="反作废后"></vxe-checkbox>
                      <vxe-checkbox label="210" content="归档后"></vxe-checkbox>
                        <vxe-checkbox label="211" content="导入后"></vxe-checkbox>
                        <vxe-checkbox label="212" content="定时任务"></vxe-checkbox>
                    </vxe-checkbox-group>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="关键字段" span="24"  field="sourceField" :item-render="{}" v-if="sendMsgForm.sourceType!==0">
                  <template #default>
                    <vxe-select width="300" v-model="sendMsgForm['sourceField']" placeholder="选择字段"   clearable  transfer>
                      <vxe-optgroup v-for="(tb ,name) in Fields" :label="tb.tableDispName" :key="name">
                        <vxe-option v-for="(item,index) in tb.Children" :key="index" :value="item.fieldName" :label="item.fieldDispName"></vxe-option>
                      </vxe-optgroup>
                    </vxe-select>
                  </template>
                </vxe-form-item>
              <vxe-form-item title="通知内容" field="sourceField" span="24" :item-render="{name:'input'}" title-overflow="ellipsis" v-else="sendMsgForm.sourceType===0"></vxe-form-item>
                <vxe-form-item title="触发字段" span="24"  field="onChangeFileld" :item-render="{}" v-if="sendMsgForm.sourceType!==0">
                  <template #default>
                    <vxe-select width="300" v-model="sendMsgForm['onChangeFileld']" placeholder="选择字段"   clearable multiple transfer>
                      <vxe-optgroup v-for="(tb ,name) in Fields" :label="tb.tableDispName" :key="name">
                        <vxe-option v-for="(item,index) in tb.Children" :key="index" :value="item.fieldName" :label="item.fieldDispName"></vxe-option>
                      </vxe-optgroup>
                    </vxe-select>
                  </template>
                </vxe-form-item>
              <vxe-form-item title="通知方式" span="24"  field="filterExpr" :item-render="{}">
                  <template #default>
                    <vxe-select v-model="sendMsgForm.filterExpr" transfer>
                      <vxe-option value="message" label="系统消息"></vxe-option>
                      <vxe-option value="dingtalk" label="钉钉"></vxe-option>
                      <vxe-option value="wxchat" label="企业微信" ></vxe-option>
                      <vxe-option value="email" label="邮件" ></vxe-option>
                      <vxe-option value="sms" label="短信" disabled></vxe-option>
                    </vxe-select>
                  </template>
                </vxe-form-item>
              <vxe-form-item field="ext.userType" title="接收人类型" :span="24" :item-render="{}">
                <template #default="{ data }">
                  <vxe-radio-group v-model="data.sendInfo.userType">
                    <vxe-radio label="sys" content="系统用户"></vxe-radio>
                    <vxe-radio label="form" content="表单用户"></vxe-radio>
                    <vxe-radio label="sql" content="SQL查询"></vxe-radio>
                    <!-- <vxe-radio label="roles" content="按角色通知"></vxe-radio> -->
                  </vxe-radio-group>
                </template>
              </vxe-form-item>

              <vxe-form-item title="接收人字段" field="ext.userField" span="24" :item-render="{}" title-overflow="title"  v-if="sendMsgForm.sendInfo.userType==='form'">
                <template #default="{data}">
                  <vxe-select v-model="data.sendInfo.userField" placeholder="请选择字段" clearable transfer>
                    <vxe-option value="CreateUser" label="制单人"></vxe-option>
                    <vxe-option v-for="(item,index) in Fields[0].Fields" :key="index" :value="item.fieldName" :label="item.fieldDispName"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-form-item>
              <vxe-form-item title="接收人取SQL查询字段(ID)" field="ext.userField" span="24" :item-render="{}" title-overflow="title"  v-if="sendMsgForm.sendInfo.userType==='sql'">
                <template #default="{data}">
                  <vxe-textarea v-model="data.sqlSchema" placeholder="请输入查询语句"  :autosize="{minRows: 5, maxRows: 15}" clearable></vxe-textarea>
                </template>
              </vxe-form-item>

              <vxe-form-item title="接收人员" field="ext.userid" :item-render="{}" span="24" v-if="sendMsgForm.sendInfo.userType==='sys'" >
                <template #default="{ data }">
                  <vxe-select v-model="data.sendInfo.userid" placeholder="请选择人员" multiple clearable transfer>
                    <vxe-option v-for="item in users" :key="item.id" :value="item.id" :label="item.userName"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-form-item>
              <!-- <vxe-form-item title="接收角色" field="ext.userid" :item-render="{}" span="24" v-if="sendMsgForm.sendInfo.userType==='roles'" >
                <template #default="{ data }">
                  <vxe-select v-model="data['roles']" placeholder="选择角色" clearable multiple transfer>
                    <vxe-option v-for="(item,index) in rotData" :value="item.id" :label="item.name"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-form-item> -->
            </vxe-form>
          </el-tab-pane>
        </el-tabs>
        <!-- <el-tabs v-show="selectTab==='pushDown'" type="border-card" style="height: 100%;">
          <el-tab-pane label="基本设置" style="height: 100%;">
            <el-form :model="form" label-width="auto" size="small" style="max-width: 600px">
              <el-form-item label="推送名称">
                <el-input placeholder="请输入名称"></el-input>
              </el-form-item>
              <el-form-item label="推送到目标表">
                <el-select
                  v-model="value"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <el-form :model="form" label-width="auto" size="small" style="max-width: 600px">
              <el-form-item label="字段选定">
                <el-row v-for="item in [{},{}]" style="margin-bottom: 10px;" gutter="10">
                  <el-col :span="8">
                    <el-select
                      v-model="value"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="8">
                    <el-select
                      v-model="value"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="danger" :icon="Delete" />
                  </el-col>
                </el-row>
                
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs> -->
      </el-col>
    </el-row>
    <filterchooseone v-show="Schoose" ref="filters" :LData="sourceFieldData" @submitt="Schooseshow"></filterchooseone>
  </div>
</template>

<script>
import {onBeforeMount, reactive, ref, toRefs, watch} from 'vue'
import {Check, Close, Delete, DocumentCopy, Edit, Plus} from '@element-plus/icons-vue'
import {delrule, listLkOdatabase, listLkSelectrule, testsql, updaterule} from '/@/api/linkoo/form/lkDataRules'
import {getDingFormList,getWxFormsData} from '/@/api/linkoo/extend'
import XEUtils from 'xe-utils'
import { getRoleList} from "/@/api/system/role";
import {ElMessage} from 'element-plus'
import Filterchooseone from '/@/components/template/filterchooseone.vue'
import {onMounted} from "@vue/runtime-core";
import VXETable from 'vxe-table'
import {getUserList} from '/@/api/system/user/index';
import {mathAll} from "../../../../../utils/mathji";


export default {
  components: {Filterchooseone},
  props: ['Template', 'Fields',"DataSource",'load'],
  setup(props, ctx) {
    let transferDatat = ref(null)
    let transferTree1 = ref(null)
    let selectTables = ref(null)
    let filters = ref(null)
    let ChoseTableFields1 = ref(null)
    let Schoose = ref(false)
    let textoption=ref([])
    let tableoption=ref([])
    let tableoption2=ref([])
    let rotData = ref([])
    let state = reactive({
      selectRow:{},
      windowHeight: document.documentElement.clientHeight,   //实时屏幕高度
      selectRule:null,
      tabelheight: 600,
      selectRuleData: [],
      updateRuleData: [],
      transferRuleData: [],
      sendMsgRuleData: [],
      sourceFieldData: [],
      FieldData: [],
      transferData: [],
      sourceField: [],
      ToFields: [],
      selectTableFields: [],
      selectTablesDataOptions: [],
      formData: {},
      sqlSchema: {},
      relationsData: [],
      selectTablesData: [],
      sourceTableData: [],
      dingforms: [],
      dingtypes: [{value: 'Text', label: '字段'}, {value: 'Date', label: '日期'}, {value: 'Table',label: '明细表'}, {value: 'Multiple', label: '多值'}, {value: 'Files', label: '附件明细表'}, {value: 'Select', label: '单选值'},
        {value: 'Object', label: '对象'}, {value: 'Voucher', label: '凭证'}, {value: 'Float',label: '数字'},{value: 'Bool', label: '布尔型'}, {value: 'Lists', label: '重复列表'},
        {value: 'DingUserID',label: '钉钉用户ID'}, {value: 'DingDeptID', label: '钉钉部门ID'}, {value: 'DingFile', label: '钉钉文件'},{value: 'DingImage', label: '钉钉图片'}, {value: 'InvoiceFile', label: '票据文件'}, {value: 'RelateField', label: '钉钉关联表单'}, {value: 'DingTJID', label: '钉钉提交人员'}, {value: 'DingTJBM', label: '钉钉提交部门'}, {value: 'DingSHR', label: '钉钉审批人员'}],
      Filter: [{type: '', title: '不查询'}, {type: '=', title: '等于'}, {type: '<>', title: '不等于'}, {
        type: '<',
        title: '小于'
      }, {type: '<=', title: '小于等于'}, {type: '>', title: '大于'}, {type: '>=', title: '大于等于'}, {
        type: 'like',
        title: '包含'
      }, {type: 'in', title: '在列表中'}, {type: 'between', title: '区间'}],
      FieldsLink: [],
      selectTab: 'select',
      users: [],
      selectForm: {sourceType:2,sourceField:[],sendInfo:{}},
      updateForm: {},
      sendMsgForm: {sendInfo:{}},
      transferForm: {sendInfo:{}},
      templates:{},
      MainTable: {},
      SelectTableToChoice: [],
      load:false,
      datatype: [{label: '文本', value: 'Text'}, {label: '数字', value: 'Number'}, {label: '日期',value: 'Date'},{label: '日期时间',value: 'DateTime'}, {label: '表格', value: 'Table'}, {label: '文件流', value: 'Files'}],
      db: [{label: '本地数据库', value: ''}],
      params: {pageNum: 1, pageSize: 1000},
      selectFilterTarget:{},
      selectFilterTargetField:'',
      filtertarget:'',
    })

    const setSelectTable = ({row}) => {
      if (row.type!=='T'){
        ElMessage.warning("请选择表!")
        return
      }else {
        if (XEUtils.filter(selectTables.value.getTableData().fullData, item => (item.tableName === row.tableName && item.ruleType === row.category)).length > 0) {
          ElMessage({        type: 'error',
            message: row.tableDispName + ' 已经选择,请不要重复选择',
          })
          return
        }
        if (XEUtils.filter(selectTables.value.getTableData().fullData, item => ((row.category === 3 && item.ruleType < row.category) || (row.category < 3 && item.ruleType === 3))).length > 0) {
          ElMessage({
            type: 'error',
            message: "外部表和内部表不能同时使用!",
          })
          return
        }
        if (XEUtils.toValueString(state.formData.allowOdata) !== '' && state.formData.allowOdata !== XEUtils.toValueString(row.od)) {
          ElMessage({
            type: 'error',
            message: '不同外部数据库不能同时使用!',
          })
          return
        }
        state.formData.allowOdata = XEUtils.toValueString(row.od)
        let record = {
          "tableID": row.tableID,
          "title": row.tableDispName,
          "name": row.tableName,
          "children": row.childrenFields.map(r=>{
            r.title=row.tableDispName+'.'+r.title
            r.name=row.tableName+'.'+r.name
            r.isF=true
            return r
          }),
          isF:false
        }


        selectTables.value.insertAt(record, -1)
        state.SelectTableToChoice=selectTables.value.getTableData().fullData
      //  state.selectTablesDataOptions=selectTables.value.getTableData().fullData
      //   state.sqlSchema.selectTablesData= selectTables.value.getTableData().fullData
        getSTF()
      }
    }
    watch(props, () => {
      if(props.load&&!state.load){
        state.sourceTableData=props.DataSource
        getList(state.selectTab)
        getTBTree()
        getDatabase()
        state.load=true

      }

    })
    onMounted(()=>{
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          // window.fullWidth = document.documentElement.clientWidth;
          state.windowHeight = window.fullHeight;  // 高
          // that.windowWidth = window.fullWidth; // 宽
        })()
      };
      getRoleList().then((res)=>{
        rotData.value=res.data.list
        console.log(res);
      })
    })
    const getList = (rule) => {
      state.params.templateID = props.Template.templateID
      switch (rule) {
        case 'select':
          state.params.type = 1
          listLkSelectrule(state.params).then(res => {
            if (res.data.list) {
              state.selectRuleData = res.data.list.map((row) => {
                row['onChangeFileld'] = row['onChangeFileld'].split(',')
                if (row.sourceType===2){
                  state.sqlSchema=XEUtils.toStringJSON(row['sourceField'])
                  state.SelectTableToChoice=state.sqlSchema.selectTablesData
                }
                return row
              })
            } else {
              state.selectRuleData = []
            }
          })
          break;
        case 'update':
          state.params.type = 2
          listLkSelectrule(state.params).then(res => {
            state.updateRuleData = res.data.list
          })
          break;
        case 'sendMsg':
          state.params.type = 4
          listLkSelectrule(state.params).then(res => {
            state.sendMsgRuleData = res.data.list&&res.data.list.map(row=>{
              row['onChangeFileld'] = row['onChangeFileld'].split(',')
              row.targetField=row.targetField.split(',')
              return row
            })
          })
          break;
        case 'transfer':
          state.params.type = 3
          listLkSelectrule(state.params).then(res => {
            if (res.data.list) {
              state.transferRuleData = res.data.list.map((row) => {
                row['sqlSchema'] =row['sqlSchema']===''?[]: JSON.parse(row['sqlSchema'])
                row['sendInfo'] = XEUtils.toStringJSON(row['sendInfo']===''?'{}':row['sendInfo'])
                return row
              })
            } else {
              state.transferRuleData = []
            }
          })
          break
      }
    }
    let transferFormt = ref(null)
    const reset = () => {
      state[state.selectTab + 'Form'] = {ruleID: 0, templateID: props.Template.templateID, iSActive: 0,sourceType:0,sendInfo:{}}
    }
    const getDatabase = () => {
      listLkOdatabase({pageNum: 1, pageSize: 1000}).then(res => {
        if (res.data.list) {
          res.data.list.forEach(row => {
            state.db.push({label: row['oDataName'] + ' ' + row['memo'], value: row['oDataName']})
          })
        }

      })
      if (state.users.length===0){
        getUserList({pageNum:1,pageSize: 1000}).then(res=>{
          state.users=res.data.userList
        })

      }
    }
    const getTBTree = () => {
      state.ToFields=[]
      XEUtils.objectEach(props.Fields, (row, key) => {
        const table = Object.assign({}, row)
        let tb = {title:  table.tableDispName , name: table.tableName, children: [], isF: false,tp:table.tableType}
        tb.children = table.Children.map((rows, index) => {
          return {
            name: table.tableName + '.' + rows.fieldName,
            title:    rows.fieldDispName ,
            isF: true,
            tp:table.tableType
          }
        })
        state.ToFields.push(tb)
      })
      ChoseTableFields1.value.reloadData(state.ToFields)
    }

    const NewRule = () => {
      state[state.selectTab + 'Form'] = {}
      reset()
    }
    const Deletet = () => {
     if (state.selectRule){
       delrule(state.selectRule.ruleID).then(res=>{
         ElMessage({
           type: 'success',
           message: "删除成功",
         })
         getList(state.selectTab)
       })

     }else{
       ElMessage({
         type: 'warning',
         message: "请先选择规则",
       })
     }

    }
    const test = () => {
      const formdata = XEUtils.clone(state[state.selectTab + 'Form'])

      console.log('formdata',formdata)
    }
    let sourceFieldsSql = ref(null)
    let sourceFieldsForm = ref(null)
    const onSubmit = async () => {
      const formdata = XEUtils.clone(state[state.selectTab + 'Form'])
      console.log(formdata.runTime);
      formdata['runTime'] = formdata['runTime']===undefined||formdata['runTime']===''?'':formdata['runTime'].join(',')
      switch (state.selectTab) {
        case 'select':
          formdata['ruleType'] = 1
          formdata['runSeq'] =XEUtils.toInteger(formdata['runSeq'])
          formdata['onChangeFileld'] = formdata['onChangeFileld'] ? formdata['onChangeFileld'].join(',') : ''
          formdata['sourceField'] = JSON.stringify(formdata['sourceField'])
          formdata['targetField'] = JSON.stringify(SelectTableFields.value ? SelectTableFields.value.getTableData().fullData : [])
            if(formdata['sourceType']===2){
              state.sqlSchema.selectTablesData= selectTables.value.getTableData().fullData.map(row=>{
                if(row.children!==undefined){
                  row.children=row.children.map(r=>{
                    delete r['_X_ROW_KEY'];return r;
                  })
                }
                delete row['_X_ROW_KEY'];return row;
              })
              state.sqlSchema.relationsData= selectRelations.value.getTableData().fullData.map(row=>{
                if(row.children!==undefined){
                  row.children=row.children.map(r=>{
                    delete r['_X_ROW_KEY'];return r;
                  })
                }
                delete row['_X_ROW_KEY'];return row;
              })
              formdata['sourceField']=JSON.stringify(state.sqlSchema)
            }
          await updaterule(formdata, formdata.ruleID).then(res => {
            ElMessage.success( res.message)
          })
          break
        case 'update':
          formdata['ruleType'] = 2
          await updaterule(formdata, formdata.ruleID).then(res => {
            VXETable.modal.message( { content: res.message, status: 'success' })
          })
          break
        case 'sendMsg':
          formdata['onChangeFileld'] = formdata['onChangeFileld'] ? formdata['onChangeFileld'].join(',') : ''
          formdata['ruleType'] = 4
          formdata['targetField'] = formdata['targetField']?formdata['targetField'].join(','):''
          await updaterule(formdata, formdata.ruleID).then(res => {
            VXETable.modal.message( { content: res.message, status: 'success' })
          })
          break
        case 'transfer':
          formdata['ruleType'] = 3
          const data=XEUtils.clone(transferDatat.value.getTableData().fullData,true)
          formdata['sqlSchema'] = JSON.stringify(clearData(data,''))
          formdata['sendInfo'] = JSON.stringify(formdata['sendInfo'])
          await updaterule(formdata, formdata.ruleID).then(res => {
            //VXETable.modal.message( { content: res.message, status: 'success' })
            ElMessage.success( res.message)
          })
          break
      }
      getList(state.selectTab);
      NewRule()
    }

    const handleClick = (tab, event) => {
      reset()
      getList(state.selectTab)
    }
    const getTabaleClick =async ({row}) => {
      const data = XEUtils.clone(row, true)
      state.selectRule=row
      if (data['runTime'] !== '') {
        data['runTime'] = data['runTime'].split(',')
      }
      if (data['sourceField'] !== ''&& data['ruleType']!==4) {
        data['sourceField'] = XEUtils.toStringJSON(data['sourceField'])
      }
      if (data['targetField'] !== ''&& data['ruleType']!==4) {
        data['targetField'] = XEUtils.toStringJSON(data['targetField'])
      }
      if (data['sendInfo'] !== '') {
        data['sendInfo'] = XEUtils.toStringJSON(data['sendInfo'])
      }
      switch (state.selectTab) {
        case 'select':
          state.selectForm = data
          break;
        case 'update':
          state.updateForm = data
          break;
        case 'sendMsg':
          state.sendMsgForm = data
          break;
        case 'transfer':
          state.transferForm = data
          // ertyui
          break;
      }
    }
    const rowclick2 = ({row}) => {
      if (row.isF || row.isF === undefined) {
        state[state.selectTab + 'Form']['filterExpr'] += row.name === undefined ? row.field : "{" + row.name + '} '
      }
    }
    let SelectTableFields = ref(null)
    const rowclick = (row) => {
      switch (state.selectTab) {
        case 'select':
          if (row.isF) {
            const record = {fieldName: row.title, tofield: row.name, field: null, type: 'value'}
            SelectTableFields.value.insertAt(record, -1)
          }
          break
        case 'transfer':
          return
          let Data = XEUtils.toTreeArray(transferDatat.value.getTableData().fullData, {clear: true})
          let N = row['name'].split('.'), T = row['title'].split('.').map(item => {
            return item.replace(/\[|\]/g, '')
          }), record = {}
          record = {
            name: N.length > 1 ? N[1] : N[0],
            title: T.length > 1 ? T[1] : T[0],
            type: N.length > 1 ? 'Text' : 'Table',
            field: null
          }
          Data.push({
            name: N.length > 1 ? N[1] : N[0],
            title: T.length > 1 ? T[1] : T[0],
            type: N.length > 1 ? 'Text' : 'Table',
            field: null,
            pname: N.length  > 1 && row.tp!==0? N[0] : ''
          })
          if (row.children !== undefined && row.children.length > 0) {
            row.children.forEach(r => {
              N = r['name'].split('.'), T = r['title'].split('.').map(item => {
                return item.replace(/\[|\]/g, '')
              })
              record = {
                name: N.length > 1 ? N[1] : N[0],
                title: T.length > 1 ? T[1] : T[0],
                type: N.length > 1 ? 'Text' : 'Table',
                field: null
              }
              Data.push({
                name: N.length > 1 ? N[1] : N[0],
                title: T.length > 1 ? T[1] : T[0],
                type: N.length > 1 ? 'Text' : 'Table',
                field: null,
                pname: N.length > 1 ? N[0] : ''
              })
            })
          }

          Data = XEUtils.orderBy(Data, 'name')
          transferDatat.value.reloadData(Data)
          break
      }
    }
    const remove =  (row) => {
      const $table =transferDatat.value
      let data=  $table.getTableData().fullData
      // console.log(data)
      // data=data.filter((item,index)=>item['_X_ROW_KEY']!==row['_X_ROW_KEY'])
      // console.log(data)
      $table.loadData(clearData(data,row['_X_ROW_KEY']))
      $table.setAllTreeExpand(true)
      // const Data = XEUtils.toTreeArray(transferDatat.value.getTableData().fullData, {clear: true}).filter(item => item.name !== row.name && item.pname !== row.name)
      // transferDatat.value.reloadData(XEUtils.orderBy(XEUtils.toTreeArray(Data, {clear: true}), 'name'))
    }
    const loadDef = () => {
     const FF=[]
      XEUtils.objectEach(props.Fields, (table, key) => {
        if(table.tableType===0){
           table.Children.map((rows, index) => {
            FF.push( {valueType: 'f',name: rows.fieldName,type: 'Text',field: rows.fieldName,children: []})
          })
        }else{
          let tb = {valueType: 'f',name: table.tableName,type: 'Table',field: table.tableName,children: []}
          tb.children = table.Children.map((rows, index) => {
            return {valueType: 'f',name: rows.fieldName,type: 'Text',field: rows.fieldName,children: []}
          })
          FF.push(tb)
        }
      })
      transferDatat.value.reloadData(FF)


    }
    const gettestSql = () => {
      const formdata = XEUtils.clone(state[state.selectTab + 'Form'])
      testsql(formdata.sqlSchema, formdata.dB).then(res => {
        if (res.code === 0) {
          let f = []
          XEUtils.objectEach(res.data.list[0], (item, key) => {
            f.push({field: key,title:key, fieldType: XEUtils.isNumber(item) ? 'Number' :XEUtils.isValidDate(XEUtils.toStringDate(item,'yyyy-MM-dd'))?'Date': 'Text'})
          })
          state.selectForm.sourceField = f
        } else {
          ElMessage({
            type: 'info',
            message: res.msg,
          })
        }
      })
    }
    const Schooseshow = ({filterText, update}) => {
      console.log(filterText,update)
      if (update) {
        // state.selectFilterTarget[state.selectFilterTargetField] = filterText
        if(state.filtertarget==='selectForm'){
          state.selectForm.filterExpr = filterText
        }else {
          state.selectFilterTarget[state.selectFilterTargetField] = filterText
        }
        // console.log(state.selectFilterTarget[state.selectFilterTargetField], "2345678");
      }
      Schoose.value = false
    }
    const showchose = ({row}) => {
      state.filtertarget='relationExpr'
      state.sourceFieldData=[]
      state.sourceFieldData=state.sourceFieldData.concat(state.ToFields,state.SelectTableToChoice)

      console.log( state.sourceFieldData)

      state.selectFilterTarget = row
      state.selectFilterTargetField = 'relationExpr'
      filters.value.filterText = XEUtils.toValueString(row.relationExpr)
      Schoose.value = true
    }
    const showchose2 = () => {
      console.log('SelectTableToChoice',state.SelectTableToChoice)
      state.filtertarget='selectForm'
      state.sourceFieldData=[]

      state.sourceFieldData=state.sourceFieldData.concat(state.ToFields,state.SelectTableToChoice)
      Schoose.value = true
    }
    const rtchange = () => {

    }
    const getSTF = () => {
      state.selectTable = []
      let dd = XEUtils.map(selectTables.value.getTableData().fullData, item => item.ruleType + item.tableName)
      state.selectTablesDataOptions = selectTables.value.getTableData().fullData.map((item, index) => {
        return {label: item.tableDispName, value: item.tableName, tableID: item.tableID}
      })
      state.selectForm.sourceField = XEUtils.filter(state.FieldData, item => XEUtils.includes(dd, item.BJ))
      state.selectForm.sourceField.forEach((item) => {
        item['FieldExpr'] = item.title
      })
    }
    let selectRelations = ref(null)
    const newRlations = () => {
      let record = {
        "sourceRelationID": 0,
        "ruleID": state.formData.dataGridID,
        "tableID1": null,
        "tableName1": null,
        "tableDispName1": null,
        "relationType": "LEFT JOIN",
        "tableID2": null,
        "tableName2": null,
        "tableDispName2": null,
        "relationExpr": null,
        "ruleType": null
      }
      const $table = selectRelations.value
      const {row: newRow} = $table.insertAt(record, -1)
      $table.setActiveCell(newRow, 'tableDispName1')
    }

    const selectRelationsremove = (row) => {
      const $table = selectRelations.value
      $table.remove(row)
    }
    const TableChangeEventDelete = ({row}) => {
      selectTables.value.remove(row)
      state.SelectTableToChoice=selectTables.value.getTableData().fullData
      getSTF()
    }

    const rowclick1 = ({row}) => {
      // let Data = {field: row.TableName + '.' + row.FieldName, type: 'value'}
      // SelectTableFields.value.insertAt(Data, -1)
      switch (state.selectTab){
        case 'select':
          if(row.isF){
            const record={fieldName:row.title,tofield:row.name,field:null,type:'value'}
            SelectTableFields.value.insertAt(record,-1)
          }
          break
        // case 'transfer':
        //   let Data=XEUtils.toTreeArray(this.$refs.transferData.getTableData().fullData,{clear:true})
        //   let N=row['name'].split('.'),T=row['title'].split('.').map(item=>{ return item.replace(/\[|\]/g,'')}),record={}
        //   record={name:N.length>1?N[1]:N[0],title:T.length>1?T[1]:T[0],type:N.length>1?'Text':'Table',field:null}
        //   Data.push({name:N.length>1?N[1]:N[0],title:T.length>1?T[1]:T[0],type:N.length>1?'Text':'Table',field:null,pname:N.length>1?N[0]:''})
        //   if(row.children!==undefined&& row.children.length>0){
        //     row.children.forEach(r=>{
        //       N=r['name'].split('.'),T=r['title'].split('.').map(item=>{ return item.replace(/\[|\]/g,'')})
        //       record={name:N.length>1?N[1]:N[0],title:T.length>1?T[1]:T[0],type:N.length>1?'Text':'Table',field:null}
        //       Data.push({name:N.length>1?N[1]:N[0],title:T.length>1?T[1]:T[0],type:N.length>1?'Text':'Table',field:null,pname:N.length>1?N[0]:''})
        //     })
        //   }
        //
        //   Data= XEUtils.orderBy(Data,'name')
        //   this.$refs.transferData.reloadData(Data)
        //   break
      }
    }
    const getTF = () => {
      getDatasource().then(res=>{
        state.sourceTableData =res.data.TemplateTable
      })
    }
    const getDingForms = () => {

      getDingFormList().then(res=>{
        ElMessage.success("执行成功")
        state.dingforms=res.data.list
      const forms=  transferFormt.value.getItems().find(row=>row.title==="钉钉表单")
        forms.itemRender
      })
    }
    const copytitle = () => {
     transferDatat.value.getTableData().fullData.map(row=>{
       row.field=row.title
       if(row.children.length>0){
         row.children.map(r=>{
           r.field=r.title
           return r
         })
       }
       return row
     })
    }
    const getWxForms = () => {
      getWxFormsData(state.transferForm.sendInfo.proc).then(res=>{
        if(res.code===0){
          ElMessage.success("执行成功")
          let txarr = []
          let tarr=[]
            XEUtils.lastArrayEach(res.data, (item, key) => {
              if(item.control==='Table'){
                tarr.push(item)
              }else{
                txarr.push(item)
              }
            })
            textoption.value=txarr
            tableoption2.value=tarr
        }

      })
    }
    const clearData=(data,xid)=>{
      return data.filter((item,index)=>item['_X_ROW_KEY']!==xid).map(row=>{
        delete row['_X_ROW_CHILD']
        delete row['_X_ROW_KEY']
        if(row.children!==undefined&&row.children.length>0){
          row.children=clearData(row.children,xid)
        }
        return row
      })
    }
    const addNew=()=>{
      const $table =transferDatat.value
      let row = {valueType:'f',name:null,type:null,field:null,children:[]}
      $table.insertAt(row, -1)
    }
    const add =  async (row,f) => {
      const $table =transferDatat.value
      let record = {valueType:'f',name:null,type:null,field:null,children:[]}
      let prow=$table.getParentRow(row)
      if(prow){
        if(f===0){
          prow.children.push(record)
        }else{
          row.children.push(record)
        }
      }else{
        if(f===0){
          const {row: newRow} = await $table.insertAt(record, -1)
          await $table.setEditRow(newRow) // 插入子节点
        }else{
          row.children.push(record)
        }

      }
      let data=$table.getTableData().fullData
      $table.loadData(clearData(data,''))
      $table.setAllTreeExpand(true)
    }
    const fieldchoice = ({ searchValue, option, group }) => {
      group.options.map(row=>{
          row.visible=true
      })
      group.options.map(row=>{
        if (row.label.indexOf(searchValue)>-1){
          row.visible=true
        }else {
          row.visible=false
        }
      })
      return true
    }
    const busthguy =(row)=>{
      return transferDatat.value.getParentRow(row)?transferDatat.value.getParentRow(row).type:transferDatat.value.getParentRow(row);
    }
    const clicktable = (item) => {
      tableoption.value=item.value.children
    }
    const doselectRow = ({row}) => {
      state.selectRow=row
    }
    const changeToField = (data) => {
      state.selectRow.fieldName=data.$select.reactData.currentOption.label
    }
    const changeField = (val,row) => {

      const t=XEUtils.arrayEach(props.Fields,tb=>{
        if(XEUtils.find(tb.Fields,f=>f.fieldName===val)){
          row['pname']=tb.tableName
        }
      })



    }
    return {
      Plus,
      DocumentCopy,
      Edit,
      Delete,
      Check,
      Close,
      transferFormt,
      transferDatat,
      getWxForms,
      tableoption2,
      SelectTableFields,
      ChoseTableFields1,
      transferTree1,
      sourceFieldsSql,
      sourceFieldsForm,
      Schoose,
      filters,
      selectTables,
      selectRelations,textoption,tableoption,
      selectRelationsremove,
      NewRule,
      Schooseshow,
      fieldchoice,
      getDingForms,
      setSelectTable,
      TableChangeEventDelete,rotData,
      showchose,
      showchose2,
      rtchange,
      Deletet,
      changeToField,
      newRlations,
      test,
      add,
      copytitle, changeField,getSTF,
      onSubmit,
      handleClick,
      doselectRow,
      ...toRefs(state),
      reset,addNew,
      getTBTree,
      getDatabase,
      getTabaleClick,
      rowclick2,
      rowclick,
      rowclick1,
      remove,
      loadDef,
      gettestSql,
      getTF,
      busthguy,
      clicktable
    }
  }
}
</script>

<style scoped>
.xxz .vxe-checkbox {
  height: 1.6em;
  padding: 0px 21px;
}

.detarule .el-tabs__content {
  height: 660px !important;
  overflow-y: auto;
}

.ju .vxe-table--render-default .vxe-body--column {
  line-height: 32px !important;
}
</style>